package com.quanquan.user.service;


import com.quanquan.user.configBeans.RabbitSender;
import com.quanquan.user.dto.UserLevelDTO;

import com.quanquan.user.entity.UserLevel;
import com.quanquan.user.entity.UserLevelRelationship;
import com.quanquan.user.exception.UserLevelException;
import com.quanquan.user.repository.UserLevelRelationshipRepository;
import com.quanquan.user.repository.UserLevelRepository;
import com.quanquan.user.request.UserLevelRequestBody;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import utils.DateUtils;
import utils.UUIDGenerator;


import java.util.HashMap;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 功能描述:会员等级逻辑层
 *
 * @ClassName: UserLevelService
 * @Author: xiaoqianh丶
 * @Date: 2019-04-01 13:31
 * @Version: V1.0
 */
@Service
public class UserLevelService {

    private final UserLevelRepository userLevelRepository;

    private final RabbitSender rabbitSender;

    private final UserLevelRelationshipRepository userLevelRelationshipRepository;

    @Autowired
    public UserLevelService(UserLevelRepository userLevelRepository, RabbitSender rabbitSender, UserLevelRelationshipRepository userLevelRelationshipRepository) {
        this.userLevelRepository = userLevelRepository;
        this.rabbitSender = rabbitSender;
        this.userLevelRelationshipRepository = userLevelRelationshipRepository;
    }

    public String createUserLevel(UserLevelRequestBody requestBody) {
        UserLevel userLevel = new UserLevel();
        userLevel.setId(UUIDGenerator.getUUID());
        userLevel.setLevelInfo(requestBody.getLevelInfo());
        userLevel.setLevelName(requestBody.getLevelName());
        userLevel.setCreateTime(DateUtils.currentDate());
        userLevel.setUpdateTime(DateUtils.currentDate());
        userLevel.setIntegralTotal(requestBody.getIntegralTotal());
        userLevel.setRemove(0);
        userLevel.setLevelStratum(requestBody.getLevelStratum());
        if (requestBody.getMultiply() == null) {
            userLevel.setMultiply(0);
        } else {
            userLevel.setMultiply(requestBody.getMultiply());
        }
        userLevelRepository.save(userLevel);
        return "添加会员等级成功";
    }


    public String updateUserLevel(UserLevelRequestBody requestBody) throws UserLevelException {
        String userLevelId = requestBody.getUserLevelId();
        UserLevel userLevel = userLevelRepository.findUserLevelByIdAndRemove(userLevelId, 0);
        if (userLevel == null) {
            throw new UserLevelException("改会员等级已不存在");
        }
        userLevel.setLevelName(requestBody.getLevelName());
        userLevel.setUpdateTime(DateUtils.currentDate());
        userLevel.setLevelInfo(requestBody.getLevelInfo());
        userLevel.setMultiply(requestBody.getMultiply());
        userLevel.setIntegralTotal(requestBody.getIntegralTotal());
        userLevelRepository.save(userLevel);
        return "跟新会员等级成功";
    }

    /**
     * 升级会员等级
     *
     * @param userId
     */
    public void upgradeLevel(String userId, Integer levelStratum) {
        //查出等级最大的levelStratum
        List<UserLevel> list = userLevelRepository.findAllByRemoveOrderByLevelStratumDesc(0);
        UserLevel userLevel = list.get(0);
        Integer levelStratum1 = userLevel.getLevelStratum();
        ++levelStratum;
        if (levelStratum <= levelStratum1) {
            removeRelationship(userId);
            UserLevelRelationship userLevelRelationship = new UserLevelRelationship();
            userLevelRelationship.setId(UUIDGenerator.getUUID());
            userLevelRelationship.setCreateTime(DateUtils.currentDate());
            userLevelRelationship.setUserId(userId);
            userLevelRelationship.setRemove(0);
            UserLevel level = userLevelRepository.findUserLevelByLevelStratumAndRemove(levelStratum, 0);
            userLevelRelationship.setUserLevelId(level.getId());

            userLevelRelationshipRepository.save(userLevelRelationship);
            //修改user的会员等级名称（通过Mq来实现吧）
            updateUserLevel(userId, level.getLevelName());

        }

    }


    /**
     * 修改用户的等级
     *
     * @param levelName
     * @param userId
     */
    private void updateUserLevel(String userId, String levelName) {
        Map<String, Object> properties = new HashMap<>();
        properties.put("levelName", levelName);
        properties.put("userId", userId);

        String exchange = "user.exchange";
        String routingKey = "user.updateLevel";

        rabbitSender.sendMessageToMQ("用户等级提升", properties, exchange, routingKey);
    }

    /**
     * 根据会员等级查询会员等级（增加一级）
     *
     * @param levelStratum
     * @return
     */
    public UserLevel findUserLevelByLevelStratum(Integer levelStratum) {
        UserLevel level = userLevelRepository.findUserLevelByLevelStratumAndRemove(levelStratum, 0);
        if (level != null) {
            return level;
        }

        return null;
    }

    /**
     * 移除关系
     *
     * @param userId
     */
    private void removeRelationship(String userId) {
        //设置原先的关系删除
        UserLevelRelationship userLevelRelationshipByUserIdAndRemove = userLevelRelationshipRepository.findUserLevelRelationshipByUserIdAndRemove(userId, 0);
        userLevelRelationshipByUserIdAndRemove.setRemove(1);
        userLevelRelationshipRepository.save(userLevelRelationshipByUserIdAndRemove);
    }


    public void createUserLevelRelationship(String userId) {
        //查询等级最低级别的等级
        UserLevel userLevel = userLevelRepository.findUserLevelByLevelStratumAndRemove(1, 0);
        UserLevelRelationship userLevelRelationship = new UserLevelRelationship();
        userLevelRelationship.setId(UUIDGenerator.getUUID());
        userLevelRelationship.setUserId(userId);
        userLevelRelationship.setCreateTime(DateUtils.currentDate());
        userLevelRelationship.setRemove(0);
        userLevelRelationship.setUserLevelId(userLevel.getId());
        userLevelRelationshipRepository.save(userLevelRelationship);
    }

    /**
     *
     *
     * @return
     */
    public List<UserLevelDTO> list() {
        List<UserLevelDTO> userLevelDTOS = new LinkedList<>();
        List<UserLevel> userLevels = userLevelRepository.findAllByRemoveOrderByLevelStratumDesc(0);

        for (UserLevel userLevel : userLevels){
            UserLevelDTO userLevelDTO =  new UserLevelDTO();
            BeanUtils.copyProperties(userLevel,userLevelDTO);
            userLevelDTO.setUserLevelId(userLevel.getId());
            userLevelDTOS.add(userLevelDTO);
        }
        return userLevelDTOS;
    }

    /**
     * 通过id查详情
     *
     * @param userLevelId
     * @return
     */
    public UserLevelDTO findByUserLevelId(String userLevelId){
        UserLevel userLevel = userLevelRepository.findUserLevelByIdAndRemove(userLevelId,0);
        if (userLevel==null){
            return null;
        }
        UserLevelDTO userLevelDTO = new UserLevelDTO();
        BeanUtils.copyProperties(userLevel,userLevelDTO);
        userLevelDTO.setUserLevelId(userLevel.getId());
        return userLevelDTO;
    }

    /**
     * 根据用户id查询会员的等级级别(翻倍的倍率)
     */
    public Integer findUserLevel(String userId) {
        UserLevelRelationship userLevelRelationship = userLevelRelationshipRepository.findUserLevelRelationshipByUserIdAndRemove(userId, 0);
        if (userLevelRelationship != null) {
            String userLevelId = userLevelRelationship.getUserLevelId();
            UserLevel userLevel = userLevelRepository.findById(userLevelId).get();
            Integer multiply = userLevel.getMultiply();
            return multiply;
        }
        //出错的情况下就按最下级的等级算
        return 1;
    }

    /**
     * 升级会员等级
     *
     * @param
     */
    public Integer upgradeLevelanual(UserLevelRequestBody requestBody) {

        String remark = null;

        Integer levelStratum = requestBody.getLevelStratum();
        String userId = requestBody.getUserId();

        //查出等级最大的levelStratum
        List<UserLevel> list = userLevelRepository.findAllByRemoveOrderByLevelStratumDesc(0);
        UserLevel userLevel = list.get(0);
        Integer levelStratum1 = userLevel.getLevelStratum();
        //根据用户id查询用户当前最高的等级
        UserLevelRelationship a = userLevelRelationshipRepository.findUserLevelRelationshipByUserIdAndRemove(userId, 0);
        String userLevelId = a.getUserLevelId();
        UserLevel userLevel1 = userLevelRepository.findById(userLevelId).get();
        Integer levelStratum2 = userLevel1.getLevelStratum();
        if (levelStratum < levelStratum2) {
            remark = "修改用户等级失败";


            return -1;
        }
        if (levelStratum <= levelStratum1) {
            removeRelationship(userId);
            UserLevelRelationship userLevelRelationship = new UserLevelRelationship();
            userLevelRelationship.setId(UUIDGenerator.getUUID());
            userLevelRelationship.setCreateTime(DateUtils.currentDate());
            userLevelRelationship.setUserId(userId);
            userLevelRelationship.setRemove(0);
            UserLevel level = userLevelRepository.findUserLevelByLevelStratumAndRemove(levelStratum, 0);
            userLevelRelationship.setUserLevelId(level.getId());

            userLevelRelationshipRepository.save(userLevelRelationship);
            //修改user的会员等级名称（通过Mq来实现吧）
            updateUserLevel(userId, level.getLevelName());
            remark = "修改用户等级为"+level.getLevelName()+"成功！";
            
            return level.getLevelStratum();
        }
        return levelStratum1;
    }
}
